function assignment = k_means(X, num_clusters)    
    N = size(X, 1);
    
    mu_indices = randperm(N, num_clusters);
    mu = X(mu_indices,:);
    
    last_assignment = zeros(N, 1);
    assignment = ones(N, 1);
    
    while ~isequal(last_assignment, assignment)
        % distances between points and cluster centers
        tx2 = sum(X.^2, 2);
        tmu2 = sum(mu.^2, 2);
        Txmu = X * mu';
        D = bsxfun(@plus, tx2, tmu2') - 2 * Txmu;
        
        % assign points to closest center
        last_assignment = assignment;
        [~, assignment] = min(D, [], 2);
        
        % new centers
        for k = 1 : num_clusters
            if (sum(assignment == k) == 0)
                mu(k,:) = X(randi(N, 1), :);
                fprintf('Cluster vanished in K-means, resetting.\n');
            else
                mu(k,:) = mean(X(assignment == k, :));
        
            end
        end
    end
end